package cn.suimg.common;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

public class GeetestUtil {

    /**
     * REGISTER_URL
     */
    private static final String REGISTER_URL = "https://api.geetest.com/register.php";

    /**
     * VALIDATE_URL
     */
    private static final String VALIDATE_URL = "https://api.geetest.com/validate.php";

    /**
     * captchaId
     */
    private static final String CAPTCHA_ID = PropertiesUtil.getValue("cn.suimg.geetest.captchaId");

    /**
     * privateKey
     */
    private static final String PRIVATE_KEY = PropertiesUtil.getValue("cn.suimg.geetest.privateKey");

    /**
     * Logger
     */
    private static final Logger logger = LoggerFactory.getLogger(GeetestUtil.class);

    /**
     * 注册一个验证码
     *
     * @param userId
     * @param clientType
     * @param ipAddress
     * @return
     */
    public static Map<String,Object> registerChallenge(String userId, String clientType, String ipAddress) {
        String json = HttpClientUtil.getData(REGISTER_URL, new HashMap<String, Object>() {{
            put("gt", CAPTCHA_ID);
            put("json_format", 1);
            put("user_id", userId);
            put("client_type", clientType);
            put("ip_address", ipAddress);
        }});
        String challenge = JSONObject.parseObject(json).getString("challenge");
        return new HashMap<String, Object>(){{
            put("success", 1);
            put("gt", CAPTCHA_ID);
            put("challenge", EncryptUtil.md5(challenge + PRIVATE_KEY));
        }};
    }

    /**
     * 校验验证码是否通过
     *
     * @param userId
     * @param clientType
     * @param ipAddress
     * @param challenge
     * @param validate
     * @param seccode
     * @return
     */
    public static boolean validateRequest(String userId, String clientType, String ipAddress, String challenge, String validate, String seccode) {
        if (validate.equals(EncryptUtil.md5(PRIVATE_KEY + "geetest" + challenge))) {
            Map<String, Object> args = new HashMap<>();
            args.put("challenge", challenge);
            args.put("validate", validate);
            args.put("seccode", seccode);
            args.put("json_format", 1);
            args.put("user_id", userId);
            args.put("client_type", clientType);
            args.put("ip_address", ipAddress);
            String json = HttpClientUtil.postData(VALIDATE_URL, args);
            String data = JSONObject.parseObject(json).getString("seccode");
            return data.equals(EncryptUtil.md5(seccode));
        }
        return false;
    }

}
